//引入node内置模块,无需下载,直接引入
const path = require('path')

//引人node内置模块glob
const glob = require('glob')

//处理html的插件
const HtmlWebpackPlugin = require('html-webpack-plugin')

//提取css插件
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

//压缩css
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')

//自动清除
const { CleanWebpackPlugin } = require('clean-webpack-plugin')


//自动读取src中所有js文件
const file = glob.sync('./src/js/*.js')
const entry = {}
file.forEach(function (v) {
  let key = path.basename(v).replace('.js', '')
  entry[key] = v;
})

//配置HTML出口插件
const html = glob.sync('./src/page/*.html');
const htmlArr = html.map(function (v) {
  return new HtmlWebpackPlugin({
    template: v,
    filename: path.basename(v), //出口名字
    chunks: [path.basename(v).replace('.html', '')]
  })
})



//暴露webpack对象
module.exports = {

  //入口entry
  entry: entry,

  //出口output
  output: {
    path: path.resolve(__dirname, 'dist'), //出口路径
    filename: 'js/[name]-[hash:5].js',//输出文件名字
    publicPath: './'
  },

  //加载器loader
  module: {
    rules: [
      //css
      {
        test: /\.css$/,
        use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../'
          }
        }, 'css-loader']  //顺序不能换
      },
      //less
      {
        test: /\.less$/,
        use: [{
          loader: MiniCssExtractPlugin.loader,
          options: {
            publicPath: '../'
          }
        }, 'css-loader', 'less-loader']
      },
      //img
      {
        test: /\.(jpg|png|gif|jpeg|jfif|webp)$/,
        loader: 'url-loader',
        options: {
          name: '[hash:16].[ext]',  // 图片输出的名字hash长度16位 默认32位
          limit: 60 * 1024,  // 小于10kb base64处理
          esModule: false, //关闭es6模块化
          outputPath: 'imgs' //输出路径
        }
      },
      //html
      {
        test: /\.html$/, // 处理html中引入img
        loader: 'html-loader'
      },
      //字体图标
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,  // 处理字体格式文件
        loader: 'file-loader',
        options: {
          name: '[hash:16].[ext]', // 输出名字
          outputPath: 'fonts' // 输出路径
        }
      }
    ]
  },

  //插件plugins
  plugins: [

    // 提取css
    new MiniCssExtractPlugin({
      filename: 'css/[name]-[hash:5].css' // 重命名输出的css
    }),

    // 压缩css
    new OptimizeCssAssetsWebpackPlugin(),


    // 删除dist目录
    new CleanWebpackPlugin()

  ].concat(htmlArr),

  //模式mode
  //mode: process.env.NODE_ENV,
  mode: 'development',

  // 开发服务器
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),// 启动服务器目录
    compress: true,// 启动gzip
    port: 9527,// 端口
    open: true,// 自动打开服务
    publicPath: '/',// 静态资源查找路径
    openPage: 'advert.html',// 打开的页面
  },
  target: 'web',// 目标是浏览器
}